import { getBindRuleListApi, getProgramListApi } from '@/services/api';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Space, Tag } from 'antd';
import { isEqual } from 'lodash';
import React, { useRef, useState } from 'react';
import BindConfigDrawer from '../Drawer/BindConfigDrawer';
import BindCouponModal from '../Drawer/BindCouponModal';
import BindRuleDrawer from '../Drawer/BindRuleDrawer';
import CreateMerchantConfig from '../Drawer/CreateMerchantConfig';

const Config: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const {
    merchan_manage_permissions_config_coupon,
    merchan_manage_permissions_config_rule,
    merchan_manage_permissions_config_edit,
    merchan_manage_permissions_config_reward,
  } = useAccess() as any;

  const [clientDrawerParams, setclientDrawerParams] = useState({
    open: false,
    info: {},
  });

  // 绑定规则弹窗
  const [bindRuleDrawerParams, setBindRuleDrawerParams] = useState({
    open: false,
    info: {},
  });

  // 绑定优惠券
  const [bindCouponDrawerParams, setBindCouponDrawerParams] = useState({
    open: false,
    info: {},
  });

  // 绑定奖励弹窗
  const [bindWardDrawerParams, setBindWardDrawerParams] = useState({
    open: false,
    info: {},
  });

  // 查询所有商户
  const { data: merchantList } = useRequest(async () => {
    const _res = await getBindRuleListApi({
      page: 1,
      size: 1000,
    });

    return _res?.data?.list;
  });

  const columns: any = [
    {
      title: '商户姓名',
      dataIndex: 'user__name__contains',
      hideInTable: true,
    },
    {
      title: '商户',
      dataIndex: ['user', 'name'],
      hideInSearch: true,
      render: (text: string, record: any) => {
        return (
          <div>
            {record?.user?.id} - {record?.user?.name}
          </div>
        );
      },
    },
    {
      title: '拉新金额',
      dataIndex: 'newcomer',
      hideInSearch: true,
      render: (text: string, record: any) => {
        return `${record?.newcomer} 元`;
      },
      width: 80,
    },
    {
      title: '车电一体金额',
      dataIndex: 'oneness',
      hideInSearch: true,
      render: (text: string, record: any) => {
        return `${record?.oneness} 元`;
      },
    },
    {
      title: '分成比例',
      dataIndex: 'divided',
      hideInSearch: true,
      render: (text: string, record: any) => {
        return `${record?.divided}%`;
      },
      width: 80,
    },
    {
      title: '绑定渠道',
      dataIndex: ['channel', 'title'],
      hideInSearch: true,
    },
    {
      title: '绑定企业',
      dataIndex: ['enterprise', 'title'],
      hideInSearch: true,
    },

    {
      title: '发展奖励',
      dataIndex: 'money_one',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '单电奖励',
      dataIndex: 'money_two',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '车电奖励',
      dataIndex: 'money_three',
      hideInSearch: true,
      width: 80,
    },

    // {
    //   title: '绑定规则',
    //   dataIndex: 'rules',
    //   hideInSearch: true,
    //   render: (text: any, record: any) => {
    //     return (
    //       <Space size={0}>
    //         {[record?.rules]?.map((item: any) => {
    //           return (
    //             <Tag color="red" key={item?.id}>
    //               {item?.title}
    //             </Tag>
    //           );
    //         })}
    //       </Space>
    //     );
    //   },
    // },
    {
      title: '权限',
      dataIndex: 'permissions',
      hideInSearch: true,
      render: (text: any, record: any) => {
        return (
          <Space size={'small'} wrap>
            {record?.permissions?.map((item: any) => {
              return (
                <Tag color="blue" key={item.id}>
                  {item?.title}
                </Tag>
              );
            })}
          </Space>
        );
      },
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 260,
      render: (text: any, record: any) => [
        merchan_manage_permissions_config_coupon && (
          <a
            key="coupon"
            onClick={() => {
              console.log('record', record);

              setBindCouponDrawerParams({
                open: true,
                info: {
                  ...record,
                  id: record?.user?.id,
                },
              });
            }}
          >
            优惠券设置
          </a>
        ),
        merchan_manage_permissions_config_rule && (
          <a
            key="editable2"
            onClick={() => {
              setBindRuleDrawerParams({
                open: true,
                info: {
                  channel: record?.channel?.id,
                  enterprise: record?.enterprise?.id,
                  id: record?.id,
                },
              });
            }}
          >
            规则配置
          </a>
        ),
        merchan_manage_permissions_config_edit && (
          <a
            key="editable"
            onClick={() => {
              setclientDrawerParams({
                open: true,
                info: {
                  ...record,
                  auths: record?.permissions?.map((_item) => _item?.id),
                  user: record?.user?.id,
                },
              });
            }}
          >
            编辑
          </a>
        ),
        merchan_manage_permissions_config_reward && (
          <a
            key="editable"
            onClick={() => {
              setBindWardDrawerParams({
                open: true,
                info: {
                  ...record,
                  money_one: record?.money_one,
                  money_two: record?.money_two,
                  money_three: record?.money_three,
                },
              });
            }}
          >
            奖励设置
          </a>
        ),
      ],
      fixed: 'right',
    },
  ];

  return (
    <>
      <ProTable
        bordered
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;
          const { data } = await getProgramListApi({
            page: current,
            size: pageSize,
            filters: JSON.stringify({
              ...ret,
            }),
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        scroll={{
          x: 1300,
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
      />

      {clientDrawerParams.open && (
        <CreateMerchantConfig
          open={clientDrawerParams.open}
          info={clientDrawerParams.info}
          close={() => {
            setclientDrawerParams({
              open: false,
              info: '',
            });
          }}
          onFinsh={() => {
            setclientDrawerParams({
              open: false,
              info: '',
            });
            actionRef.current?.reload();
          }}
        ></CreateMerchantConfig>
      )}

      {bindRuleDrawerParams?.open && (
        <BindRuleDrawer
          open={bindRuleDrawerParams?.open}
          onFinsh={() => {
            setBindRuleDrawerParams({
              open: false,
              info: '',
            });
            actionRef.current?.reload();
          }}
          close={() => {
            setBindRuleDrawerParams({
              open: false,
              info: '',
            });
          }}
          info={bindRuleDrawerParams.info}
          options={merchantList}
        />
      )}

      {bindWardDrawerParams?.open && (
        <BindConfigDrawer
          open={bindWardDrawerParams?.open}
          onFinsh={() => {
            setBindWardDrawerParams({
              open: false,
              info: '',
            });
            actionRef.current?.reload();
          }}
          close={() => {
            setBindWardDrawerParams({
              open: false,
              info: '',
            });
          }}
          info={bindWardDrawerParams.info}
        />
      )}

      {bindCouponDrawerParams?.open && (
        <BindCouponModal
          open={bindCouponDrawerParams?.open}
          onFinsh={() => {
            setBindCouponDrawerParams({
              open: false,
              info: undefined,
            });
            // actionRef.current?.reload();
          }}
          close={() => {
            setBindCouponDrawerParams({
              open: false,
              info: undefined,
            });
          }}
          info={bindCouponDrawerParams?.info}
        />
      )}
    </>
  );
};

export default React.memo(Config, (prev, next) => isEqual(prev, next));
